package com.java1234.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import com.java1234.dao.IBorrowerDao;
import com.java1234.model.Book;
import com.java1234.model.Borrower;
import com.java1234.util.StringUtil;

public class BorrowerImpl implements IBorrowerDao {
	/**
	 * 数据库借阅者信息添加
	 */
	public int add(Connection con, Borrower borrower) throws Exception {
		String sql = "insert into t_borrower values(?,?,?)";
		PreparedStatement pstmt = con.prepareStatement(sql);
		pstmt.setString(1, borrower.getBorrowerAccount());
		pstmt.setString(2, borrower.getBorrowerName());
		pstmt.setString(3, borrower.getPassword());
		int i = pstmt.executeUpdate();

		return i;
	}

	/**
	 * 数据库借阅者信息查询
	 * 
	 * @param con
	 * @param book
	 * @return
	 * @throws Exception
	 */
	public ResultSet list(Connection con, Borrower borrower) throws Exception {
		StringBuffer sb = new StringBuffer("select * from t_borrower");
		if (StringUtil.isNotEmpty(borrower.getBorrowerAccount())) {
			sb.append(" and borrowerAccount like '%" + borrower.getBorrowerAccount() + "%'");
		}
		if (StringUtil.isNotEmpty(borrower.getBorrowerName())) {
			sb.append(" and borrowerName like '%" + borrower.getBorrowerName() + "%'");
		}
		PreparedStatement pstmt = con.prepareStatement(sb.toString().replaceFirst("and", "where"));
		ResultSet i = pstmt.executeQuery();
		return i;
	}

	/**
	 * 数据库借阅者信息删除
	 * 
	 * @param con
	 * @param id
	 * @return
	 * @throws Exception
	 */
	public int delete(Connection con, String borrowerAccount) throws Exception {
		String sql = "delete from t_borrower where borrowerAccount=?";
		PreparedStatement pstmt = con.prepareStatement(sql);
		pstmt.setString(1, borrowerAccount);
		int i = pstmt.executeUpdate();

		return i;
	}

	/**
	 * 数据库借阅者信息修改
	 * 
	 * @param con
	 * @param book
	 * @return
	 * @throws Exception
	 */
	public int update(Connection con, Borrower borrower) throws Exception {
		String sql = "update t_borrower set borrowerName=?,password=? where borrowerAccount=?";
		PreparedStatement pstmt = con.prepareStatement(sql);
		pstmt.setString(1, borrower.getBorrowerName());
		pstmt.setString(2, borrower.getPassword());
		pstmt.setString(3, borrower.getBorrowerAccount());

		int i = pstmt.executeUpdate();

		return i;
	}

	/**
	 * 数据库指定借阅者账户下是否存在借阅者
	 * 
	 * @param con
	 * @param bookTypId
	 * @return
	 * @throws Exception
	 */
	public boolean existBorrowerByBorrowerAccount(Connection con, String borrowerAccount) throws Exception {
		String sql = "select * from t_borrower where borrowerAccount=?";
		PreparedStatement pstmt = con.prepareStatement(sql);
		pstmt.setString(1, borrowerAccount);
		ResultSet rs = pstmt.executeQuery();
		return rs.next();
	}
}
